package com.heima.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.common.rides.RedisCacheService;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.UserRelationDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.service.UserFollowService;
import com.heima.utils.threadlocal.AppThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Slf4j
@Transactional
public class UserFollowServiceImpl implements UserFollowService {

    @Autowired
    private RedisCacheService redisCacheService;

    @Override
    public ResponseResult follow(UserRelationDto dto) {
        //1.参数校验
        if (dto == null || dto.getArticleId() == null || dto.getOperation() < 0 || dto.getOperation() > 1) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.判断登录用户
        ApUser user = AppThreadLocalUtil.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //3.判断关注还是取消关注
        if (dto.getOperation()==0){
            redisCacheService.hPut("BEHAVIOR_FOLLOW_"+dto.getArticleId(),user.getId().toString(), JSON.toJSONString(dto));
        }else {
            redisCacheService.hDelete("BEHAVIOR_FOLLOW_"+dto.getArticleId(),user.getId().toString());
        }
        return ResponseResult.okResult(null);
    }
}
